<template>
  <div class="dialog">
    <el-dialog
      title="完善设备信息"
      :visible.sync="showDialog"
      width="55%"
      top="0"
      :close-on-click-modal="false"
      @close="cancel"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="first" />
        <el-tab-pane label="购置信息" name="second" />
        <el-tab-pane label="报废信息" name="third" />
        <el-tab-pane label="其他信息" name="fourth" />
      </el-tabs>
      <el-form
        v-if="activeName==='first'"
        ref="ruleForm"
        label-position="left"
        :model="formData"
        :rules="rules"
        class="el-form"
      >
        <el-form-item label="设备名称：" prop="equipmentName" class="w50p">
          <el-input
            v-model="formData.equipmentName"
            placeholder="请输入设备名称"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="所属设备型号：" prop="equModelCode" class="w50p">
          <el-select
            v-model="formData.equModelCode"
            filterable
            clearable
            :disabled="!editStatus"
          >
            <el-option
              v-for="(item,index) in equModelArr"
              :key="index+'equModelCode'"
              :label="item.modelName"
              :value="item.equModelCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否展示工况数据：" prop="operationMode" class="w50p">
          <el-select
            v-model="formData.operationMode"
            filterable
            clearable
            :disabled="!editStatus"
          >
            <el-option
              v-for="item in yesOrNoList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否可自动驾驶：" prop="selfDriving" class="w50p">
          <el-select
            v-model="formData.selfDriving"
            filterable
            clearable
            :disabled="!editStatus"
          >
            <el-option
              v-for="item in yesOrNoList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!editStatus"
          label="设备图片："
          prop="picture"
          class="w50p"
        >
          <el-image :src="pictureData" :preview-src-list="pictureList" />
        </el-form-item>
        <el-form-item v-else label="设备图片：" prop="picture" class="w50p">
          <el-upload
            action
            :http-request="modeUpload"
            :file-list="uploadPictureList"
            accept=".png, .jpg, .jpeg"
            :on-remove="handleRemove"
          >
            <el-button type="text" class="add-many">
              <i class="el-icon-plus"></i>
            </el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          v-if="!editStatus"
          label="设备视频："
          prop="video"
          class="w50p"
        >
          <div style="width:100%">
            <video :src="videoUrl" class="video-con" controls></video>
            <!-- <p class="hang-font">暂无内容</p> -->
          </div>
        </el-form-item>
        <el-form-item v-else label="设备视频：" prop="video" class="w50p">
          <el-upload
            action
            :http-request="modeUpload"
            :file-list="videoUrlList"
            accept=".mp4"
            :on-remove="handleRemoveV"
          >
            <el-button type="text" class="add-many">
              <i class="el-icon-plus"></i>
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-form
        v-if="activeName==='second'"
        ref="ruleForm1"
        label-position="left"
        :model="formData1"
        :rules="rules1"
        class="el-form"
      >
        <el-form-item label="设备名称：" prop="equipmentCode" class="w50p">
          <!-- <el-select v-model="formData1.equipmentCode" filterable clearable placeholder="请选择设备名称">
              <el-option
                v-for="(item,index) in equipmentArr"
                :key="index+'.equipmentCode'"
                :label="item.equipmentName"
                :value="item.equipmentCode"
              />
          </el-select>-->
          <el-input
            v-model="formData1.equipmentName"
            placeholder="请输入设备名称"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="设备质保日期 ：" class="w50p" prop="warrantyDate">
          <el-date-picker
            v-model="formData1.warrantyDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
            :disabled="!editStatus"
          />
        </el-form-item>
        <el-form-item label="购置数量：" prop="num" class="w50p">
          <el-input
            v-model="formData1.num"
            placeholder="请输入购置数量"
            :disabled="!editStatus"
          />
          <el-select
            v-model="formData1.unitNo"
            filterable
            clearable
            placeholder="单位选择"
            :disabled="!editStatus"
          >
            <el-option
              v-for="(item,index) in unitArr"
              :key="index+'unit'"
              :label="item.unitName"
              :value="item.unitNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="购置总金额：" prop="total" class="w50p">
          <el-input
            v-model="formData1.total"
            placeholder="请输入购置总金额"
            :disabled="!editStatus"
          />元
        </el-form-item>
        <el-form-item label="购置日期：" class="w50p" prop="purchaseDate">
          <el-date-picker
            v-model="formData1.purchaseDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
            :disabled="!editStatus"
          />
        </el-form-item>
        <el-form-item label="供应商：" prop="taxpayerNumber" class="w50p">
          <el-input
            v-model="formData1.taxpayerNumber"
            placeholder="请输入供应商"
            :disabled="!editStatus"
          />
        </el-form-item>
        <el-form-item label="购置补贴金额：" prop="subsidy" class="w50p">
          <el-input
            v-model="formData1.subsidy"
            placeholder="请输入购置补贴金额"
            :disabled="!editStatus"
          />元
        </el-form-item>
        <el-form-item label="备注：" prop="remark" class="w50p">
          <el-input
            v-model="formData1.remark"
            type="textarea"
            placeholder="请输入备注(选填)"
            :autosize="{ minRows: 2, maxRows: 4 }"
            clearable
            :disabled="!editStatus"
          />
        </el-form-item>
      </el-form>
      <el-form
        v-if="activeName==='third'"
        ref="ruleForm2"
        label-position="left"
        :model="formData2"
        :rules="rules2"
        class="el-form"
      >
        <el-form-item label="设备名称：" prop="equipmentCode" class="w50p">
          <!-- <el-select v-model="formData2.equipmentCode" filterable clearable placeholder="请选择设备名称" :disabled="nowChanceStau==='edit'?true:false">
              <el-option
                v-for="item in equipmentArr"
                :key="item.equipmentCode"
                :label="item.equipmentName"
                :value="item.equipmentCode"
              />
          </el-select>-->
          <el-input
            v-model="formData2.equipmentName"
            placeholder="请输入设备名称"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="已使用(天)：" prop="used" class="w50p">
          <el-input
            v-model="formData2.used"
            placeholder="请输入已使用天数"
            :disabled="!editStatus"
          />
        </el-form-item>
        <el-form-item label="报废补贴金额：" prop="subsidy" class="w50p">
          <el-input
            v-model="formData2.subsidy"
            placeholder="请输入报废补贴金额"
            :disabled="!editStatus"
          />
        </el-form-item>
        <el-form-item label="报废日期：" class="w50p" prop="scrapDate">
          <el-date-picker
            v-model="formData2.scrapDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            clearable
            :disabled="!editStatus"
          />
        </el-form-item>
        <el-form-item label="备注：" prop="remark" class="w50p">
          <el-input
            v-model="formData2.remark"
            type="textarea"
            placeholder="请输入备注(选填)"
            :autosize="{ minRows: 2, maxRows: 4 }"
            clearable
            :disabled="!editStatus"
          />
        </el-form-item>
      </el-form>
      <el-form
        v-if="activeName==='fourth'"
        label-position="left"
        :model="formData2"
        :rules="rules2"
        class="el-form"
      >
        <el-form-item
          v-if="!editStatus"
          label="设备说明书："
          prop="equipmentCode"
          class="w50p"
        >
          <ul>
            <li v-for="item,index in docuemntList" :key="index">
              <span class="pointer" @click="downPDF(item)">{{ item.fileName }}</span>
            </li>
          </ul>
        </el-form-item>
        <el-form-item v-else label="设备说明书：" prop="equipmentCode" class="w50p">
          <el-upload
            action
            :http-request="modeUpload"
            :file-list="docuemntList"
            accept=".pdf"
            :on-remove="handleRemoveD"
          >
            <el-button type="text" class="add-many">
              <i class="el-icon-plus"></i>
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button
          v-if="judgePermission(138,'edit') && editStatus === false"
          type="primary"
          class="editbtn"
          @click="editStatus = true"
        >
          <i class="el-icon-edit-outline"></i>
          <span>修改完善信息</span>
        </el-button>
        <el-button
          v-if="judgePermission(138,'edit') && editStatus === true"
          type="primary"
          class="savebtn"
          @click="save()"
        >保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import equipStandingBookApi from "@/api/processing-management/equip-manage/equip-standing-book";
import equipScrapRecordApi from "@/api/processing-management/equip-manage/equip-scrap-record";
import equipPurchaseRecordApi from "@/api/processing-management/equip-manage/equip-purchase-record";
import documentApi from "@/api/processing-management/document";
import dataItemManageApi from "@/api/processing-management/basic-info-manage/data-item-manage";
import { mapGetters } from "vuex";
export default {
  name: "",
  components: {},
  props: {
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {};
      }
    },
    equModelArr: {
      type: [Array],
      default: () => {
        return [];
      }
    }
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value % 1 === 0) {
          callback();
        } else {
          return callback(new Error("请输入整数！"));
        }
      }
    };
    return {
      // 图片文件
      modePicture: {},
      // 视频文件
      modeVideo: {},
      // 文档文件
      modeDocument: [],
      // 上传视频文件后返回的视频id
      equipmentVideoIdList: [],
      // 视频地址
      videoUrl: "",
      // 存放视频的数组
      videoUrlList: [],
      // 存放文档的数组
      docuemntList: [],
      // 选中的tab页
      activeName: "first",
      // 是否处于编辑状态
      editStatus: false,
      // 图片预览状态
      dialogVisible: false,
      // 存放图片列表的数组
      uploadPictureList: [],
      // 图片预览url
      dialogImageUrl: "",
      pictureData: "",
      pictureList: [],
      formData: {},
      rules: {
        equModelCode: [
          {
            required: true,
            message: "请选择设备型号",
            trigger: ["change", "blur"]
          }
        ],
        equipmentName: [
          {
            required: true,
            message: "请输入设备名称",
            trigger: ["change", "blur"]
          }
        ],
        operationMode: [
          {
            required: true,
            message: "请选择是否展示工况数据",
            trigger: ["change", "blur"]
          }
        ],
        selfDriving: [
          {
            required: true,
            message: "请选择是否可自动驾驶",
            trigger: ["change", "blur"]
          }
        ]
      },
      yesOrNoList: [
        { name: "是", id: true },
        { name: "否", id: false }
      ],
      // 添加修改
      parameterList: [],
      formData1: {},
      rules1: {
        equipmentCode: [
          {
            required: true,
            message: "请选择设备名称",
            trigger: ["change", "blur"]
          }
        ],
        num: [
          {
            required: true,
            message: "请输入购置数量",
            trigger: ["change", "blur"]
          }
        ],
        total: [
          {
            required: true,
            message: "请输入购置总金额",
            trigger: ["change", "blur"]
          }
        ],
        warrantyDate: [
          {
            required: true,
            message: "请选择设备质保日期",
            trigger: ["change", "blur"]
          }
        ],
        purchaseDate: [
          {
            required: true,
            message: "请选择购置日期",
            trigger: ["change", "blur"]
          }
        ]
      },
      // 单位
      unitArr: [],
      formData2: {},
      rules2: {
        equipmentCode: [
          {
            required: true,
            message: "请选择设备名称",
            trigger: ["change", "change"]
          }
        ],
        used: [{ validator: checkInt, trigger: ["change", "blur"] }],
        subsidy: [
          {
            pattern: /^-?\d{1,16}(?:\.\d{1,8})?$/,
            message: "请输入报废补贴金额(数字)",
            trigger: ["change", "blur"]
          }
        ],
        scrapDate: [
          {
            required: true,
            message: "请选择报废日期",
            trigger: ["change", "change"]
          }
        ]
      },
      equipmentArr: [],
      showDialog: this.show,
      // 报废信息
      scrapObject: {},
      // 购置信息
      purchaseObject: {},
      scrapNowChanceStau: "add",
      purchaseNowChanceStau: "add",
      statusArr: [
        {
          name: "启用",
          id: "ENABLE"
        },
        {
          name: "废弃",
          id: "DISCARD"
        },
        {
          name: "维修中",
          id: "REPAIRING"
        },
        {
          name: "禁用",
          id: "DISABLE"
        }
      ]
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    show(v) {
      this.showDialog = v;
    },
    editObject(v) {
      if (v && v.equipmentCode) {
        this.formData = {
          equipmentCode: this.editObject.equipmentCode,
          equipmentName: this.editObject.equipmentName
        };
        this.formData1 = {
          equipmentCode: this.editObject.equipmentCode,
          equipmentName: this.editObject.equipmentName
        };
        this.formData2 = {
          equipmentCode: this.editObject.equipmentCode,
          equipmentName: this.editObject.equipmentName
        };
        this.formData = this.editObject;
        this.scrapNowChanceStau = "";
        this.purchaseNowChanceStau = "";
        this.scrapObject = {};
        this.purchaseObject = {};
        this.queryScrap(v.equipmentCode);
        this.queryPurchase(v.equipmentCode);
        this.queryDocument(v.equipmentCode);
      }
    }
  },
  created() {},
  mounted() {
    this.queryUnitList();
    this.queryEquipment();
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    // 保存上传文件
    modeUpload(item) {
      if (item.file.type === "video/mp4") {
        this.modeVideo = item.file;
        // 调用上传视频的方法
        this.handleSuccessV();
      } else if (
        item.file.type === "image/jpg" ||
        item.file.type === "image/png" ||
        item.file.type === "image/jpeg"
      ) {
        this.modePicture = item.file;
        this.uploadPictureList.push(item.file);
        // 调用上传图片的方法
        this.handleSuccess();
      } else {
        this.modeDocument = item.file;
        this.docuemntList.push(item.file);
        // 调用上传文档的方法
        this.handleSuccessD();
      }
    },
    // 图片上传
    handleSuccess() {
      let that = this;
      let fd = new FormData();
      fd.append("file", this.modePicture);
      fd.append("equipmentCode", this.editObject.equipmentCode);
      documentApi.addPictureList(fd).then(res => {
        if (res.code === 1) that.$message.success("上传成功！");
        else that.$message.error(res.msg);
      });
    },
    // 文档上传
    handleSuccessD() {
      let that = this;
      let fd = new FormData();
      console.log(this.modeDocument);
      fd.append("file", this.modeDocument);
      fd.append("fileName", this.modeDocument.name);
      fd.append("equipmentCode", this.editObject.equipmentCode);
      documentApi.addDocument(fd).then(res => {
        if (res.code === 1) that.$message.success("上传成功！");
        else that.$message.error(res.msg);
      });
    },
    // 视频上传
    handleSuccessV() {
      let that = this;
      let fd = new FormData();
      fd.append("file", this.modeVideo);
      fd.append("videoName", this.modeVideo.name);
      documentApi.addEquipmentVideo(fd).then(res => {
        if (res.code === 1) {
          that.equipmentVideoIdList.push(res.data.equipmentVideoId);
          that.$message.success("上传成功！");
        } else that.$message.error(res.msg);
      });
    },
    // 图片删除
    handleRemove(file) {
      let that = this;
      documentApi.delPictureList(file.equipmentPictureId).then(res => {
        if (res.code === 1) that.$message.success("删除成功！");
        else that.$message.error(res.msg);
      });
    },
    // 视频删除
    handleRemoveV(file) {
      let that = this;
      // console.log(file)
      documentApi.delVideoList(file.equipmentVideoId).then(res => {
        if (res.code === 1) {
          that.videoUrl = "";
          that.$message.success("删除成功！");
        } else that.$message.error(res.msg);
      });
    },
    // 文档删除
    handleRemoveD(file) {
      let that = this;
      console.log(file);
      documentApi.delDocument(file.equipmentFileId).then(res => {
        if (res.code === 1) {
          that.$message.success("删除成功！");
        } else that.$message.error(res.msg);
      });
    },
    async queryDocument(params) {
      // 查询当前设备图片
      documentApi.queryPictureList(params).then(res => {
        if (res.code === 1) {
          let data = res.data;
          this.uploadPictureList = data;
          this.pictureList = [];
          if (this.uploadPictureList.length > 0) {
            this.uploadPictureList.forEach(a => {
              a.name = a.pictureName;
              this.pictureList.push(
                "data:application/*;base64," + a.pictureData
              );
            });
          }
          this.pictureData = this.pictureList[0];
        }
      });
      // 查询当前设备视频id
      const res = await documentApi.queryVideoIdList(params);
      if (res.code === 1) {
        console.log(res);
        this.videoUrlList = [];
        this.videoUrlList = res.data;
        if (this.videoUrlList.length > 0) {
          this.videoUrlList.forEach(a => {
            a.name = a.videoName;
          });
          this.videoUrl = `https://gateway.matefarm.net/v3/equipment-base/v1/equipmentVideo/getFileById?equipmentVideoId=${this.videoUrlList[0].equipmentVideoId}&databaseName=DB_TDW1_TENANT`;
        }
      }
      // 查询当前设备文档文件
      documentApi.queryDocument(params).then(res => {
        if (res.code === 1) {
          console.log("---", res.data);
          let data = res.data;
          this.docuemntList = data;
          if (this.docuemntList.length > 0) {
            this.docuemntList.forEach(a => {
              a.name = a.fileName;
            });
          }
        }
      });
    },
    // 文档下载
    downPDF(file) {
      documentApi
        .downPDF({ equipmentFileId: file.equipmentFileId })
        .then((res = {}) => {
          if (window.navigator.msSaveBlob) {
            // IE
            // IE无法打开Blob URL链接，所以不能预览只能通过window.navigator.msSaveBlob下载
            // 注：msSaveBlob的第二个参数要有.pdf后缀，不然IE下载后是没有后缀的文件
            const blob = new window.Blob([res.data], {
              type: "application/pdf;charset-UTF-8"
            });
            window.navigator.msSaveBlob(blob, `${filename}.pdf`);
          } else {
            const blob = new window.Blob([res], {
              type: "application/pdf;charset-UTF-8"
            });
            const href = URL.createObjectURL(blob);
            window.open(href);
          }
        });
    },
    queryScrap(params) {
      equipScrapRecordApi.query(params).then(res => {
        if (res.code === 1) {
          let data = res.data || {};
          this.scrapObject = data;
          if (this.scrapObject.equipmentCode) {
            this.scrapNowChanceStau = "edit";
            this.formData2 = this.scrapObject;
          } else {
            this.scrapNowChanceStau = "add";
          }
        }
      });
    },
    queryPurchase(params) {
      equipPurchaseRecordApi.query(params).then(res => {
        if (res.code === 1) {
          let data = res.data || {};
          this.purchaseObject = data;
          if (this.purchaseObject.equipmentCode) {
            this.purchaseNowChanceStau = "edit";
            this.formData1 = this.purchaseObject;
          } else {
            this.purchaseNowChanceStau = "add";
          }
        }
      });
    },
    // 单位
    queryUnitList() {
      this.unitArr = [];
      dataItemManageApi.queryUnit({}).then(res => {
        if (res.code === 1) {
          let data = res.data || {};
          this.unitArr = data;
        } else {
          this.$message.error("单位名称给获取失败");
        }
      });
    },
    queryEquipment() {
      this.equipmentArr = [];
      equipScrapRecordApi.queryEquipment({}).then(res => {
        if (res.code === 1) {
          let data = res.data || [];
          for (var i in data) {
            this.equipmentArr.push({
              equipmentName: data[i],
              equipmentCode: i
            });
          }
        }
      });
    },
    save() {
      if (this.activeName === "first") {
        this.saveInfo("ruleForm");
      }
      if (this.activeName === "second") {
        this.savePurchase("ruleForm1");
      }
      if (this.activeName === "third") {
        this.saveScrap("ruleForm2");
      }
      this.editStatus = false;
    },
    saveInfo(formData) {
      this.$refs[formData].validate(async valid => {
        if (valid) {
          // 编辑接口
          var index = this.statusArr.findIndex(
            a => a.name === this.formData.status
          );
          if (index !== -1) {
            this.formData.status = this.statusArr[index].id;
          }
          equipStandingBookApi.edit(this.formData).then(res => {
            if (res.code === 1) {
              this.$message.success("修改成功！");
              this.close();
            }
          });
          equipStandingBookApi.bindEquipmentAndVideo({
            equipmentCode: this.editObject.equipmentCode,
            equipmentVideoIdList: this.equipmentVideoIdList
          });
        } else {
          return false;
        }
      });
    },
    savePurchase(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.purchaseNowChanceStau === "edit") {
            equipPurchaseRecordApi.edit(this.formData1).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.purchaseNowChanceStau === "add") {
            this.formData1.organizationMark = sessionStorage.organizationNo;
            equipPurchaseRecordApi.add(this.formData1).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    saveScrap(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          this.formData2.subsidy = Number(this.formData2.subsidy);
          if (this.scrapNowChanceStau === "edit") {
            equipScrapRecordApi.edit(this.formData2).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (this.scrapNowChanceStau === "add") {
            equipScrapRecordApi.add(this.formData2).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.close();
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    close() {
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
      this.editStatus = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.add-many {
  border: 1px solid #6ecae3;
  width: 40px;
  height: 40px;
  padding: 0;
  background-color: transparent;
  line-height: 40px;
  border-radius: 4px;
  color: rgb(161, 154, 154);
  font-weight: 600;
  i {
    font-size: 40px;
  }
}
.pointer {
  cursor: pointer;
}
::v-deep .el-upload-dragger {
  width: 330px;
}
.video-con {
  width: 100%;
  height: 200px;
}
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 160px !important;
}
::v-deep .el-tabs__item.is-active {
  color: #006e91;
}
::v-deep .el-image-viewer__close {
  color: #006e91;
}
::v-deep .el-tabs__item {
  font-size: 16px;
  &:hover {
    color: #006e91;
  }
}
::v-deep .el-tabs__active-bar {
  background-color: #006e91;
}
</style>
